// assets/test/apply-corner.ts
import { _decorator, Component, ImageAsset, Sprite, Texture2D, UITransform, Vec2 } from 'cc';
import { patternConfigs } from './pattern-config';
import { createSpriteFrameFromPixelData, generatePixelData, VariationIntensity } from './imageGenerator';
import RenderContentData from './renderContentData';
const { ccclass, executeInEditMode, property } = _decorator;

@ccclass('ApplyCorner')
@executeInEditMode
export class ApplyCorner extends Component {
  @property(Texture2D)
  logo: Texture2D = null!;

  // 输出画布的尺寸（像素宽/高），用于承载 a、b 两个形状
  private outW = 950;
  private outH = 1280;
  // 承载像素的缓冲区，格式为 RGBA8888（一维数组）
  private out: Uint8Array;
  // 与材质绑定的纹理对象，负责把缓冲区显示到屏幕
  private texture: Texture2D;
  // 每帧执行的下落步数（数值越大，下落越快）
  private stepsPerFrame = 10;
  // 是否完成初始化（创建纹理并绑定材质）
  private initialized = false;

  // 把一块源图拷贝到目标缓冲的指定位置（透明像素不拷贝）
  private blit(
    dst: Uint8Array,
    dstW: number,
    dstH: number,
    src: Uint8Array,
    srcW: number,
    srcH: number,
    dx: number,
    dy: number
  ) {
    // 遍历源图的每个像素：源 (x,y) → 目标 (dx+x, dy+y)
    for (let y = 0; y < srcH; y++) {
      const yy = dy + y;
      if (yy < 0 || yy >= dstH) continue;
      for (let x = 0; x < srcW; x++) {
        const xx = dx + x;
        if (xx < 0 || xx >= dstW) continue;
        // 源像素在 src 数组中的字节起点；目标像素在 dst 数组中的字节起点
        const si = (y * srcW + x) * 4;
        const di = (yy * dstW + xx) * 4;
        // 源像素 alpha 为 0 则视为空，不拷贝
        const sa = src[si + 3];
        if (sa === 0) continue;
        // 直接拷贝 RGBA（此处不做颜色混合）
        dst[di] = src[si];
        dst[di + 1] = src[si + 1];
        dst[di + 2] = src[si + 2];
        dst[di + 3] = sa;
      }
    }
  }

  // 将一个像素从 srcIdx 移动到 dstIdx（把源位置清空）
  private movePixel(srcIdx: number, dstIdx: number) {
    // 读取源 RGBA
    const r = this.out[srcIdx];
    const g = this.out[srcIdx + 1];
    const b = this.out[srcIdx + 2];
    const a = this.out[srcIdx + 3];
    // 写入目标 RGBA
    this.out[dstIdx] = r;
    this.out[dstIdx + 1] = g;
    this.out[dstIdx + 2] = b;
    this.out[dstIdx + 3] = a;
    // 清空源位置（置为透明）
    this.out[srcIdx] = 0;
    this.out[srcIdx + 1] = 0;
    this.out[srcIdx + 2] = 0;
    this.out[srcIdx + 3] = 0;
  }

  // 执行一次“逐步下落”迭代：从倒数第二行开始向上扫描
  // 对每个非空像素，优先尝试直落；若下方被占据，尝试左下；再尝试右下
  // 返回本轮是否发生了移动，用于驱动每帧上传纹理
  private stepFalling(): boolean {
    let moved = false;
    // 从 outH-2 行到第 0 行：避免同帧内重复处理刚刚移动到下一行的像素
    for (let y = this.outH - 2; y >= 0; y--) {
      // 当前行的字节基址；下一行（下方）的字节基址
      const rowBase = y * this.outW * 4;
      const belowBase = (y + 1) * this.outW * 4;
      for (let x = 0; x < this.outW; x++) {
        // 当前像素字节起点，获取其 alpha 判断是否为空
        const di = rowBase + x * 4;
        const a = this.out[di + 3];
        if (a === 0) continue;
        // 直落：检查正下方是否为空
        const downIdx = belowBase + x * 4;
        if (this.out[downIdx + 3] === 0) {
          this.movePixel(di, downIdx);
          moved = true;
          continue;
        }
        // 左下：优先尝试左下为空
        if (x > 0) {
          const dl = belowBase + (x - 1) * 4;
          if (this.out[dl + 3] === 0) {
            this.movePixel(di, dl);
            moved = true;
            continue;
          }
        }
        // 右下：其后尝试右下为空
        if (x < this.outW - 1) {
          const dr = belowBase + (x + 1) * 4;
          if (this.out[dr + 3] === 0) {
            this.movePixel(di, dr);
            moved = true;
            continue;
          }
        }
      }
    }
    return moved;
  }

  onLoad() {
    // 生成两个形状 a（心形）、b（I 形），数据格式为 RGBA8888
    const a = generatePixelData(patternConfigs['HEART'], true, 'strong');
    const b = generatePixelData(patternConfigs['I'], true, 'strong');
    // 初始化输出缓冲，并将 a、b 拷贝到缓冲区的初始位置
    this.out = new Uint8Array(this.outW * this.outH * 4);
    this.blit(this.out, this.outW, this.outH, a.pixelData, a.width, a.height, 0, 0);
    this.blit(this.out, this.outW, this.outH, b.pixelData, b.width, b.height, a.width + 10, 0);

    // 以缓冲区创建纹理与精灵帧，绑定到材质属性
    const { spriteFrame, texture } = createSpriteFrameFromPixelData(this.out, this.outW, this.outH);
    const sprite = this.getComponent(Sprite)!;
    const mat = sprite.customMaterial || sprite.sharedMaterial;
    mat.setProperty('spriteSize', new Vec2(this.node.getComponent(UITransform).width, this.node.getComponent(UITransform).height));
    mat.setProperty('textureX', texture);
    this.texture = texture;
    this.initialized = true;
  }

  update() {
    // 若未初始化或无纹理引用，跳过
    if (!this.initialized || !this.texture) return;
    // 每帧推进若干步下落（stepsPerFrame），若发生移动则上传纹理数据
    let moved = false;
    for (let i = 0; i < this.stepsPerFrame; i++) {
      if (this.stepFalling()) moved = true;
      else break;
    }
    if (moved) this.texture.uploadData(this.out);
  }


}